import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import varType from './varType'
import qs from 'qs'

let loadingInstance
const loadingOpts = {
  spinner: 'el-icon-loading',
  background: 'rgba(0, 0, 0, 0.1)',
  text: '拼命加载中',
  lock: true
}

const closePreMsg = () => {
  try {
    MessageBox.close()
  } catch (e) {
    // 关闭上次弹框
  }
}

const emptyFilter = obj => {
  if (!obj) {
    return
  }
  Object.keys(obj).forEach(key => {
    const value = obj[key]
    const type = varType(value)
    if (type === 'number') {
      if (value === null) {
        delete obj[key]
      }
    } else if (type === 'array') {
      let i = 0
      for (const _obj of value) {
        emptyFilter(_obj, obj[key][i++])
      }
    } else if (type === 'object') {
      emptyFilter(value, obj[key])
    } else {
      if (value === '') {
        delete obj[key]
      }
    }
  })
  return obj
}
// create an axios instance
const service = axios.create({
  baseURL: 'ptbk',
  // baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60 // request timeout
})
// service.defaults.headers.post['Content-Type'] = 'application/json'
// request interceptor
service.interceptors.request.use(
  config => {
    const { showLoading = true, timeout = 1000 * 60 } = config.opts || {}
    config.timeout = timeout
    if (showLoading) {
      if (loadingInstance) {
        loadingInstance.close()
      }
      loadingInstance = Loading.service(loadingOpts)
    }
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    const { method } = config
    if (method === 'post') {
      config.headers['Content-Type'] = 'application/json'
    } else if (method === 'get') {
      // 过滤空字段
      const params = config.params
      emptyFilter(params)
      const url = config.url
      if (!url.includes('?') && params) {
        config.url = url + '?' + qs.stringify(params)
        delete config.params
      }
    }
    return config
  },
  error => {
    loadingInstance && loadingInstance.close()
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const opts = response.config.opts
    let showError = true
    if (opts) {
      showError = opts.showError
    }

    loadingInstance && loadingInstance.close()
    const res = response.data

    const { code, token, data, message } = res
    if (code === -3) {
      closePreMsg()
      MessageBox.confirm('登录超时，是否重新登录?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        store.dispatch('login/relogin')
      })
      return
    }else if(code === -7){
      closePreMsg()
      MessageBox.confirm('用户已在其他地方登录,是否重新登录?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        store.dispatch('login/relogin')
      })
      return
    }else if (code === -6) {
      closePreMsg()
      MessageBox.alert(message, '提示', {
        confirmButtonText: '知道了',
        type: 'warning'
      }).then(() => {
        store.dispatch('login/relogin')
      })
      return
    }
    let type = 'info'
    switch (code) {
      case -1:
      case -5:
        type = 'error'
        break
      case -2:
      case -4:
        type = 'warning'
        break
    }
    // if the custom code is not 20000, it is judged as an error.
    if (code === undefined) {
      return res
    }
    if (code !== 0) {
      showError !== false && Message({
        showClose: true,
        customClass: type === 'warning' ? 'hey-message-warning' : '',
        message: message || 'Error',
        type,
        duration: 5 * 1000
      })
      return Promise.reject(new Error(message || 'Error'))
    } else {
      if (token && data) {
        data.token = token
      }
      return data
    }
  },
  error => {
    loadingInstance && loadingInstance.close()
    Message.closeAll()
    console.log('err' + error) // for debug
    Message({
      showClose: true,
      message: '网络请求失败，请稍后再试',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
